package com.example.superjson.util;

import java.io.BufferedInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.StringWriter;
import java.io.UnsupportedEncodingException;
import java.net.HttpURLConnection;
import java.net.URL;

import org.apache.commons.io.IOUtils;

public class HTTPUtil {

	private static final String TAG_STRING = "HTTPUtil"; 
	public static String downloadUrl(String myurl) throws IOException {
		InputStream is = null;
		HttpURLConnection conn = null;
		try {
			URL url = new URL(myurl);
			conn = (HttpURLConnection) url.openConnection();
			conn.setReadTimeout(10000 /* milliseconds */);
			conn.setConnectTimeout(15000 /* milliseconds */);
			conn.setRequestMethod("POST");
			conn.setDoInput(true);
			conn.connect();
			// Starts the query
			int response = conn.getResponseCode();
			InputStream in = new BufferedInputStream(conn.getInputStream());
			// Log.d("DEBUG_TAG", "The response is: " + response);
//			is = conn.getInputStream();

			// Convert the InputStream into a string
			String contentAsString = readIt(in);
//			String contentAsString = readIt(is);
			return contentAsString;

			// Makes sure that the InputStream is closed after the app is
			// finished using it.
		} finally {
			if (is != null) {
				is.close();
			}
			
			if(conn != null){
				conn.disconnect();
			}
		}
	}

	public static String downloadUrlPost(String myurl) throws IOException {
		InputStream is = null;
		HttpURLConnection conn = null;
		try {
			URL url = new URL(myurl);
			conn = (HttpURLConnection) url.openConnection();
			conn.setReadTimeout(10000 /* milliseconds */);
			conn.setConnectTimeout(15000 /* milliseconds */);
			conn.setRequestMethod("POST");
			conn.setDoInput(true);
			conn.connect();
			// Starts the query
			int response = conn.getResponseCode();
			InputStream in = new BufferedInputStream(conn.getInputStream());
			// Log.d("DEBUG_TAG", "The response is: " + response);
//			is = conn.getInputStream();

			// Convert the InputStream into a string
			String contentAsString = readIt(in);
//			String contentAsString = readIt(is);
			return contentAsString;

			// Makes sure that the InputStream is closed after the app is
			// finished using it.
		} finally {
			if (is != null) {
				is.close();
			}
			
			if(conn != null){
				conn.disconnect();
			}
		}
	}

	
	// Reads an InputStream and converts it to a String.
	public static String readIt(InputStream stream) throws IOException,
			UnsupportedEncodingException {
		StringWriter writer = new StringWriter();
		IOUtils.copy(stream, writer, "UTF-8");
		return writer.toString();
	}
}
